package com.wngbms.netty._12dubbo.client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Data
@Slf4j
public class NettyClientHandler extends ChannelInboundHandlerAdapter implements Callable {

    private ChannelHandlerContext context;
    private String result;
    private String para;

    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    CountDownLatch countDownLatch = new CountDownLatch(1);
    CountDownLatch countDownLatch1 = new CountDownLatch(1);
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("ctx:{}", ctx);
        context = ctx;
//        condition.notify();
        countDownLatch.countDown();
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("read, {}", msg);
        result = msg.toString();
//        condition.notify();
        countDownLatch1.countDown();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("err ", cause);
    }

    @Override
    public Object call() throws Exception {
//        condition.await();
        countDownLatch.await();
        log.info("==========");
        context.writeAndFlush(para);
//        condition.await();

        countDownLatch1.await();

        log.info(">>>>>>>>>>>>>>");
        return result;
    }
}
